package com.kuwei.servlet.frame;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSONArray;
import com.kuwei.base.ParamerException;
import com.kuwei.base.ServiceException;

/**
 * 控制类 程序总入口 所有请求都经过这个类
 * 所有请求参考以下链接
 * http://localhost:8080/Shop/ControlServlet/doPost.action?methodName=updateTest&serviceName=testServ
 * @author zyc
 *
 */
@Controller
@RequestMapping("ControlServlet")
public class ControlServlet {
	
	private static final Logger logger = LoggerFactory.getLogger(ControlServlet.class);
	
	private String passUri = null;
	
	public ControlServlet(){
		
	}
	/**
	 * 程序入口
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/doPost.action")
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException{	
		if (logger.isDebugEnabled()) {
			logger.debug("enter method:ControlServlet.doPost");
		}
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "private");
		response.setHeader("Pragma", "no-cache");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		String serviceName = request.getParameter("serviceName");
		if (StringUtils.isEmpty(serviceName)) {
			logger.error("Parameter[serviceName] is empty, please check it!");
			return;
		}
		String methodName = request.getParameter("methodName");
		if (StringUtils.isEmpty(methodName)) {
			logger.error("Parameter[methodName] is empty, please check it!");
			return;
		}
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
		BaseServlet serviceInstance = null;
		try {
			serviceInstance = (BaseServlet) context.getBean(serviceName);
		} catch (Exception e) {
			logger.error("bean {} not exists!!!",serviceName, e);
			return;
		}
		
		Class<? extends BaseServlet> clazz = serviceInstance.getClass();
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		Method method = null;
		try {
			method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class, Map.class);
		} catch (NoSuchMethodException e) {
			logger.error("bean={} not exists method {}", serviceName,methodName, e);
			return;
		} catch (SecurityException e) {
			logger.error("bean={} not exists public method {}",serviceName,methodName, e);
			return;
		}
		try {
			method.invoke(serviceInstance, request, response, rtnMap);
		} catch (IllegalAccessException e) {
			logger.error("get error in [bean={},method={}]",serviceName,methodName, e);
		} catch (InvocationTargetException e){
			InvocationTargetExceptionHandle(e,serviceName,methodName);
		} catch (Exception e){
			
		}
//		HttpSession session = request.getSession();  
//		Cookie cookie = new Cookie("JSESSIONID", session.getId());  
//        cookie.setPath("/KuWei");  
		PrintWriter out = response.getWriter();
		out.println(JSONArray.toJSONString(rtnMap));
		out.flush();
		out.close();
		if (logger.isDebugEnabled()) {
			logger.debug("leave method:ControlServlet.doPost");
		}
	}
	
	/**
	 * Description:反射异常以及调用执行反射方法抛出的异常
	 * @param e
	 * @param rtnMap
	 * @param errorMap
	 */
	private static void InvocationTargetExceptionHandle(InvocationTargetException e,String serviceName,String methodName){
		Class c=e.getTargetException().getClass();
		String msg="";
		if(c==ServiceException.class){
			msg = "Service服务异常";
		} else if(c==ParamerException.class){
			msg = "参数异常";
		} else{
			msg = "系统异常";
		}
		logger.error("get error in [bean={},method={}] {}:",serviceName,methodName,msg,e.getTargetException().getMessage()); //日志记录完整信息
	}
	
	public static void main(String[] args) {
		try{
			throw new NamingException();
		} catch(Exception e){
			String code ="0";
			String message = "error";
			logger.error("code:{},message:{}",code,message,e);
		}
	}
}
